package com.sprd.simple.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;

import com.sprd.simple.adapter.DefaultPageAdapter;
import com.sprd.simple.launcher.R;
import com.sprd.simple.model.IconInfo;
import com.sprd.simple.model.LauncherGridView;
import com.sprd.simple.util.AppIntentUtil;
import com.sprd.simple.util.UnreadInfoUtil;
import com.sprd.simple.util.UnreadMessageContentObserver;

import java.util.ArrayList;

import android.provider.Settings;
import android.widget.TextClock;
import android.database.ContentObserver;
import android.net.Uri;

/**
 * Created by SPRD on 2016/7/19.
 */
public class DefaultWorkspaceFragment extends LauncherFragment implements AdapterView.OnItemClickListener, AdapterView.OnClickListener {

    private static final String TAG = "DefaultFragment";

    public LinearLayout mClockView = null;
    private TextClock mDateView = null;
    private DateFormatObserver mDateFormatObserver;

    public static int messageCount = 0;

    private UnreadMessageContentObserver mUnreadObserver;
    private Context mContext;

    private final static int REFRESH = 1000;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REFRESH:
                    mAdapter.notifyDataSetChanged();
                    return;

                case UnreadInfoUtil.MMSSMS_UNREAD_MESSAGE:
                    messageCount = (int) msg.obj;
                    Log.i(TAG, "Handler messageCount = " + messageCount);
                    break;

                default:
                    break;
            }
            mAdapter.notifyDataSetChanged();
        }
    };

    class UnreadInfoThread extends Thread {
        @Override
        public void run() {
            messageCount = UnreadInfoUtil.getUnreadMessageCount(mContext);
            Log.i(TAG, "UnreadInfoThread messageCount = " + messageCount);
            mHandler.sendEmptyMessage(REFRESH);
        }
    }

    public DefaultWorkspaceFragment() {
        super();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mContext = getContext();
        View view = inflater.inflate(R.layout.fragment_default_pager, container, false);
        initView(view);
        createObserver();
        registerContentObservers();
        refreshDateFormat();
        new UnreadInfoThread().start();
        return view;
    }

    private void initView(View view) {
        mClockView = (LinearLayout) view.findViewById(R.id.default_clock_view);
        mDateView = (TextClock) mClockView.findViewById(R.id.format_date_view);
        mClockView.requestFocus();
        mClockView.setSelected(true);
        mClockView.setOnClickListener(this);

        appNameForTTS = new String[]{
                getResources().getString(R.string.camera_name),
                getResources().getString(R.string.contacts_name),
                getResources().getString(R.string.message_name),
                getResources().getString(R.string.phone_name)};

        mGridView = (LauncherGridView) view.findViewById(R.id.default_grid_view);
        mAdapter = new DefaultPageAdapter(getData(), mContext, appNameForTTS, mGridView);
        mGridView.setAdapter(mAdapter);
        mGridView.setSelector(getResources().getDrawable(R.color.transparent));
        mGridView.setOnItemClickListener(this);
    }

    private final class DateFormatObserver extends ContentObserver {

        public DateFormatObserver() {
            super(new Handler());
        }

        @Override
        public void onChange(boolean selfChange, Uri uri) {
            refreshDateFormat();
        }
    }

    public void refreshDateFormat() {
        Log.i(TAG, "refreshDateFormat");
        String dateFormat;
        int date_format = Settings.System.getInt(mContext.getContentResolver(), "date_set_format", 0);
        int date_separate = Settings.System.getInt(mContext.getContentResolver(), "date_set_separate", 0);
        switch (date_format) {
            case 1:
                dateFormat = "E yyyy/MM/dd";
                break;
            case 2:
                dateFormat = "E MM/dd/yyyy";
                break;
            default:
                dateFormat = "E dd/MM/yyyy";
                break;
        }
        switch (date_separate) {
            case 1:
                dateFormat = dateFormat.replaceAll("/", ".");
                break;
            case 2:
                dateFormat = dateFormat.replaceAll("/", "-");
                break;
            default:
                break;
        }
        mDateView.setFormat24Hour(dateFormat);
        mDateView.setFormat12Hour(dateFormat);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mClockView.isFocused()) {
            mGridView.setFocusable(false);
        } else {
            mGridView.setFocusable(true);
            mGridView.requestFocus();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterContentObservers();
    }

    private void createObserver() {
        mDateFormatObserver = new DateFormatObserver();
        mUnreadObserver = new UnreadMessageContentObserver(mContext, mHandler);
    }

    private void registerContentObservers() {
        mContext.getContentResolver().registerContentObserver(
                Settings.System.getUriFor("date_set_format"), false, mDateFormatObserver);
        mContext.getContentResolver().registerContentObserver(
                Settings.System.getUriFor("date_set_separate"), false, mDateFormatObserver);
        mContext.getContentResolver().registerContentObserver(UnreadInfoUtil.MMSSMS_CONTENT_URI, true, mUnreadObserver);
    }

    private void unregisterContentObservers() {
        mContext.getContentResolver().unregisterContentObserver(mDateFormatObserver);
        mContext.getContentResolver().unregisterContentObserver(mUnreadObserver);
    }

    private ArrayList getData() {
        ArrayList<IconInfo> list = new ArrayList<>();

        IconInfo camera = new IconInfo();
        camera.setIconName(getResources().getString(R.string.camera_name));
        camera.setIconImage(R.drawable.app_camera);
        camera.setPackageName("com.huawei.camera");
        list.add(camera);

        IconInfo contact = new IconInfo();
        contact.setIconName(getResources().getString(R.string.contacts_name));
        contact.setIconImage(R.drawable.app_contacts);
        contact.setPackageName(getResources().getString(R.string.contacts_package));
        list.add(contact);

        IconInfo message = new IconInfo();
        message.setIconName(getResources().getString(R.string.message_name));
        message.setIconImage(R.drawable.app_message);
        message.setPackageName("com.android.messaging");
        list.add(message);

        IconInfo phone = new IconInfo();
        phone.setIconName(getResources().getString(R.string.phone_name));
        phone.setIconImage(R.drawable.app_phone);
        phone.setPackageName("com.android.contacts");
        list.add(phone);

        return list;
    }

    @Override
    public void onClick(View v) {
        if (v == mClockView) {
            Intent intent = new Intent();
            intent.setClassName("com.android.deskclock", "com.android.deskclock.AlarmsMainActivity");
            AppIntentUtil.intentSetFlag(intent);
            startActivity(intent);
        }
    }

    /**
     * Each item click and enter different app
     *
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent();
        switch (position) {
            case 0:
                //com.huawei.camera/.controller.CameraActivity
                intent.setClassName("com.huawei.camera", "com.huawei.camera.controller.CameraActivity");
                startActivity(intent);
                break;
            case 1:
                // cmp=com.android.messaging/.ui.conversationlist.ConversationListActivity}
                intent.setClassName(getResources().getString(R.string.contacts_package),
                        getResources().getString(R.string.contacts_activity));
                startActivity(intent);
                break;
            case 2:
                //com.android.contacts/com.android.mms.ui.ConversationList
                intent.setClassName("com.android.contacts",
                        "com.android.mms.ui.ConversationList");
                startActivity(intent);
                break;
            case 3:
                intent = new Intent(Intent.ACTION_DIAL);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

}
